package rapier.sso.server.utils;

import javax.validation.constraints.NotEmpty;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import rapier.sso.server.constant.RapierServerConstant;

/**
 * JWTUtils, 生成Token等
 * 
 * @author chenkw
 *
 */
public class TokenUtils {

	/**
	 * 生成签名
	 *
	 * @return 加密的token
	 */
	public static String makeToken(@NotEmpty Long appId, @NotEmpty Long userId) {
		Algorithm algorithm = Algorithm.HMAC256(RapierServerConstant.RAPIER_SERVER_SECRET);
		// 附带username信息
		return JWT.create().withClaim("appId", appId).withClaim("userId", userId).sign(algorithm);
	}

	/**
	 * 生成签名
	 *
	 * @return 加密的token
	 */
	public static String makeToken(@NotEmpty Long userId) {
		Algorithm algorithm = Algorithm.HMAC256(RapierServerConstant.RAPIER_SERVER_SECRET);
		// 附带username信息
		return JWT.create().withClaim("userId", userId).sign(algorithm);
	}

	/**
	 * 生成签名
	 *
	 * @return 加密的token
	 */
	public static String makeAppTicket(Long appId, String ticketgrant) {
		Algorithm algorithm = Algorithm.HMAC256(RapierServerConstant.RAPIER_SERVER_SECRET);
		return JWT.create().withClaim("appId", appId).withClaim("ticketgrant", ticketgrant).sign(algorithm);
	}

	/**
	 * 生成签名
	 *
	 * @return 加密的token
	 */
	public static String makeAppTicketgrant(Long appId) {
		Algorithm algorithm = Algorithm.HMAC512(RapierServerConstant.REDIS_RAPIER_APP_TICKET_GRAND);
		return JWT.create().withClaim("appId", appId).sign(algorithm);
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return token中包含的用户名
	 */
	public static Long getUserId(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim("userId").asLong();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return token中包含的用户名
	 */
	public static Long getAppId(String ticket) {
		try {
			DecodedJWT jwt = JWT.decode(ticket);
			return jwt.getClaim("appId").asLong();
		} catch (JWTDecodeException e) {
			return null;
		}
	}
}
